package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                role.setPermissions(permissions);
            }
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        userDao.add(user);
        setUserAndRole(user.getId(),roleIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean)throws Exception{
        //利用mybatis的分页助手插件进行分页查询
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //根据条件进行分页查询
        Page<User> page=userDao.selectByCondition(queryPageBean.getQueryString());
        long total = page.getTotal();
        List<User> rows = page.getResult();
        for (User row : rows) {
            Date birthday = row.getBirthday();
            String birthday_string = DateUtils.parseDate2String(birthday);
            row.setBirthday_string(birthday_string);
        }
        return new PageResult(total,rows);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleByUserId(Integer id) {
        return userDao.findRoleByUserId(id);
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        //先修改用户信息
        userDao.updateUser(user);
        //修改中间便，比较好的办法是先删除，在重新关联
        userDao.deleteRoleIdByUserId(user.getId());
        //重新关联
        setUserAndRole(user.getId(),roleIds);
    }

    @Override
    public void delete(Integer id) {
        //删除用户的时候要考虑和角色的中间表是否有关联，有就不可以删除
        int count=userDao.findCountByUserId(id);
        if (count>0){
            //有关联
            userDao.deleteUser_Role(id);

        }
        userDao.deleteById(id);
    }

    @Override
    public String findUserImg(String username) {
        String img = userDao.findImg(username);
        if (img!=null){
            return img;
        }
       return null;
    }

    //添加用户角色提出来的方法
    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        if (roleIds !=null&&roleIds.length>0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }
    @Override
    public void exchange(String username, String encode) {
        Map map=new HashMap();
        map.put("username",username);
        map.put("encode",encode);
        userDao.exchange(map);
    }

    @Override
    public String check(String username) {
        return userDao.check(username);
    }

}

